package com.njtoyo.taxi.admin.service.data.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.njtoyo.taxi.admin.handler.FilterHandler;
import com.njtoyo.taxi.admin.library.Const;
import com.njtoyo.taxi.admin.mapper.master.mapper.DriverServiceLogMapper;
import com.njtoyo.taxi.admin.mapper.secondary.entity.cache.CacheCustomer;
import com.njtoyo.taxi.admin.mapper.secondary.entity.data.DashboardIncomeDaily;
import com.njtoyo.taxi.admin.mapper.secondary.entity.data.DashboardOrderDaily;
import com.njtoyo.taxi.admin.mapper.secondary.enums.DataIncomeThroughType;
import com.njtoyo.taxi.admin.mapper.secondary.enums.DataIncomeType;
import com.njtoyo.taxi.admin.mapper.secondary.enums.DataOrderType;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.cache.CacheCustomerMapper;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.data.DashboardIncomeDailyMapper;
import com.njtoyo.taxi.admin.mapper.secondary.mapper.data.DashboardOrderDailyMapper;
import com.njtoyo.taxi.admin.rest.wrapper.data.data_analysis.OverviewWrapper;
import com.njtoyo.taxi.admin.service.data.OverviewService;
import com.taxi.entity.common.RestResult;
import com.njtoyo.taxi.entity.backend.AdminUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@DS(Const.SECONDARY_DS)
public class OverviewServiceImpl implements OverviewService {

    @Autowired
    private DashboardOrderDailyMapper dashboardOrderDailyMapper;

    @Autowired
    private DashboardIncomeDailyMapper dashboardIncomeDailyMapper;

    @Autowired
    private DriverServiceLogMapper driverServiceLogMapper;

    @Autowired
    private CacheCustomerMapper cacheCustomerMapper;

    @Override
    public RestResult mainData(AdminUser adminUser, OverviewWrapper wrapper) {
        FilterHandler filterHandler = new FilterHandler(adminUser, wrapper.getCantonId(), wrapper.getCompanyId());

        Map<String, Object> res = new HashMap<>();
        // 订单
        if (adminUser.getResourceNames().contains("data_analysis_overview_order")) {
            res.put("order", getOrderData(filterHandler, wrapper.getStartTime(), wrapper.getEndTime()));
        }
        // 收入
        if (adminUser.getResourceNames().contains("data_analysis_overview_income")) {
            res.put("income", getIncomeData(filterHandler, wrapper.getStartTime(), wrapper.getEndTime()));
        }
        // 叫车乘客总数
        if (adminUser.getResourceNames().contains("data_analysis_overview_customer")) {
            res.put("customer", getCustomerData(filterHandler, wrapper.getStartTime(), wrapper.getEndTime()));
        }
        // 出车数，出车司机数
//        if (adminUser.getResourceNames().contains("data_analysis_overview_taxi") || adminUser.getResourceNames().contains("data_analysis_overview_driver")) {
//            DateTime startDate = DateTime.of(wrapper.getStartTime());
//            DateTime endDate = DateTime.of(DateUtil.endOfDay(wrapper.getEndTime()));
//            Map working = new HashMap();
//            switch (filterHandler.getFilterType()) {
//                case platform:
//                    working = driverServiceLogMapper.getWorkingCount(null, null, startDate, endDate);
//                    break;
//                case canton:
//                    working = driverServiceLogMapper.getWorkingCount(filterHandler.getCantonIds(), null, startDate, endDate);
//                    break;
//                case company:
//                    working = driverServiceLogMapper.getWorkingCount(null, filterHandler.getCompanyIds(), startDate, endDate);
//                    break;
//            }
//            // 车俩
//            if (adminUser.getResourceNames().contains("data_analysis_overview_taxi")) {
//                Long taxiCount = (Long) working.getOrDefault("taxiCount", 0);
//                // 翻倍率
//                Double customer = filterHandler.getFakeMultiple().getActiveTaxi();
//                if (Objects.nonNull(customer)) {
//                    taxiCount = (long) (Long.parseLong(taxiCount.toString()) * customer);
//                }
//                res.put("taxi", taxiCount);
//            }
//            // 司机
//            if (adminUser.getResourceNames().contains("data_analysis_overview_driver")) {
//                Long driverCount = (Long) working.getOrDefault("driverCount", 0);
//                // 翻倍率
//                Double customer = filterHandler.getFakeMultiple().getActiveDriver();
//                if (Objects.nonNull(customer)) {
//                    driverCount = (long) (Long.parseLong(driverCount.toString()) * customer);
//                }
//                res.put("driver", driverCount);
//            }
//        }

        return RestResult.success(res);
    }

    /**
     * 乘客
     */
    private Long getCustomerData(FilterHandler filterHandler, Date start, Date end) {
        QueryWrapper<CacheCustomer> wrapper = new QueryWrapper<>();
        Long count = 0L;
        String startDate = DateUtil.format(start, DatePattern.NORM_DATE_PATTERN);
        String endDate = DateUtil.format(end, DatePattern.NORM_DATE_PATTERN);
        wrapper.between("stats_date", startDate, endDate);
        switch (filterHandler.getFilterType()) {
            case canton:
            case company:
                wrapper.in("canton_id", filterHandler.getCantonIds());
                break;
        }
        List<CacheCustomer> list = cacheCustomerMapper.selectList(wrapper);
        if (!list.isEmpty()) {
            List<Integer> customerIds = new ArrayList<>();
            for (CacheCustomer item: list) {
                List<Integer> res = (List<Integer>) JSON.parse(item.getRealtimeCall());
                customerIds.addAll(res);
            }
            customerIds = new ArrayList<>(new LinkedHashSet<>(customerIds));
            count = (long) customerIds.size();
        }

        // 翻倍率
        Double customer = filterHandler.getFakeMultiple().getActiveCustomer();
        if (Objects.nonNull(customer)) {
            count = (long) (Long.parseLong(count.toString()) * customer);
        }

        return count;
    }

    /**
     * 收入
     */
    private Map<String, Object> getIncomeData(FilterHandler filterHandler, Date start, Date end) {
        Map<String, Object> incomeData = new HashMap<>();
        QueryWrapper<DashboardIncomeDaily> wrapper = new QueryWrapper<>();
        wrapper.between("stats_date", start, end)
                .eq("through_type", DataIncomeThroughType.all);
        switch (filterHandler.getFilterType()) {
            case canton:
                wrapper.in("canton_id", filterHandler.getCantonIds());
                break;
            case company:
                wrapper.in("company_id", filterHandler.getCompanyIds());
                break;
        }
        wrapper.groupBy("type");
        wrapper.select("type, IFNULL(SUM(value), 0) AS total");
        List<Map<String, Object>> result = dashboardIncomeDailyMapper.selectMaps(wrapper);

        Map result1 = result.stream().collect(Collectors.toMap((p) -> p.get("type"), (p) -> p.get("total")));
        Arrays.stream(DataIncomeType.values()).forEach(i -> {
            incomeData.put(i.name(), result1.getOrDefault(i.getCode(), 0));
        });

        // 翻倍率
        Double ride = filterHandler.getFakeMultiple().getRide();
        if (Objects.nonNull(ride)) {
            incomeData.forEach((k, v) -> incomeData.put(k, (Double.parseDouble(v.toString()) * ride)));
        }

        return incomeData;
    }

    /**
     * 订单
     */
    private Map<String, Object> getOrderData(FilterHandler filterHandler, Date start, Date end) {
        Map<String, Object> orderData = new HashMap<>();
        QueryWrapper<DashboardOrderDaily> wrapper = new QueryWrapper<>();
        wrapper.between("stats_date", start, end);
        wrapper.in("type", DataOrderType.pickOnline, DataOrderType.pickScan, DataOrderType.simpleCall, DataOrderType.phoneCall);
        switch (filterHandler.getFilterType()) {
            case canton:
                wrapper.in("canton_id", filterHandler.getCantonIds());
                break;
            case company:
                wrapper.in("company_id", filterHandler.getCompanyIds());
                break;
        }
        wrapper.groupBy("type");
        wrapper.select("type, IFNULL(SUM(num), 0) AS total");
        List<Map<String, Object>> result = dashboardOrderDailyMapper.selectMaps(wrapper);

        Map result1 = result.stream().collect(Collectors.toMap((p) -> p.get("type"), (p) -> p.get("total")));
        orderData.put(DataOrderType.pickOnline.name(), result1.getOrDefault(DataOrderType.pickOnline.getCode(), 0));
        orderData.put(DataOrderType.pickScan.name(), result1.getOrDefault(DataOrderType.pickScan.getCode(), 0));
        orderData.put(DataOrderType.simpleCall.name(), result1.getOrDefault(DataOrderType.simpleCall.getCode(), 0));
        orderData.put(DataOrderType.phoneCall.name(), result1.getOrDefault(DataOrderType.phoneCall.getCode(), 0));

        // 翻倍率
        Double ride = filterHandler.getFakeMultiple().getRide();
        if (Objects.nonNull(ride)) {
            orderData.forEach((k, v) -> orderData.put(k, (int) (Integer.parseInt(v.toString()) * ride)));
        }

        return orderData;
    }
}
